import React from 'react';
import { Modal, Row, Col, Button, Table, Select, Switch, Pagination, message, Form, Input, Card } from 'antd';
import { $http } from 'containers/config/https';
import store from 'store';

const { Option } = Select;
const formItemLayout = {    // label 和input宽度
	labelCol: { span: 7 },
	wrapperCol: { span: 17 },
};
const FormItem = Form.Item;
const AddPayment = Form.create()(
	class extends React.Component {
		constructor(props) {
			super(props);
			var userData = JSON.parse(sessionStorage.getItem('userData'));
			this.state = {
				userData,
				visible: false,
				tableData: [],
				startDate: undefined, // 开始日期
				endDate: undefined, // 截止日期
				status: undefined, // 单据状态
				rowId: '', // 选中行id
				total: 0, // 总条数
				page: 1, // 页数
				pageSize: 10, // 每页的条数
				stateCode: {},
				locId: '',
				showIcon: false,
				ChineseEnglishSize: {}, // 中英翻译
				language: JSON.parse(window.sessionStorage.userData),
				columnsRight: [],
				modalColumnTotal: '',
				loading: false
			}
			// 药品的数据表头

			this.columnsRight = [
				{
					key: 1,
					title: '药品名称',
					dataIndex: 'stockDesc',
					align: "center",
					width: '14%'
				},
				{
					key: 2,
					title: '货位号',
					dataIndex: 'stockBin',
					align: "center",
					width: '12%',
					sorter: (a, b) => a.stockBin - b.stockBin,
				},
				{
					key: 3,
					title: '库存大类',
					dataIndex: 'stkCatDesc',
					align: "center",
					width: '12%',
				},
				{
					key: 4,
					title: '库存子类',
					dataIndex: 'stkSubCat',
					align: "center",
					width: '12%',
				},
				{
					key: 5,
					title: '包装规格',
					dataIndex: 'stockSpec',
					align: "center",
					width: '12%',
				},
				{
					key: 6,
					title: '冰结数量(库存单位)',
					dataIndex: 'accPurQty',
					align: "center",
					width: '12%',
				},
				{
					key: 7,
					title: '冰结数量(基本单位)',
					dataIndex: 'accBaseQty',
					align: "center",
					width: '12%',
				},
				{
					key: 8,
					title: '生产厂家',
					dataIndex: 'manfDesc',
					align: "center",
					width: '14%',
				}
			]
		}

		componentDidMount() {
			// 获取列表数据
			this.props.onRef(this);
			this.getDetailTableColumns();
			let leftList = document.querySelectorAll('.leftListHeight  .ant-table-body');
			if (leftList.length > 0) {
				leftList[0].style.height = store.getState().tableHeight.y - 105 + 'px';
			}
			let listData = document.querySelectorAll('.listHeight  .ant-table-body');
			if (listData.length > 0) {
				listData[0].style.height = store.getState().tableHeight.y - 105 + 'px';
			}
		}

		//props变化是即使更新props
		componentWillReceiveProps(props) {
			this.setState({ stateCode: props.SelectData, ChineseEnglishSize: props.ChineseEnglishSize })
		}

		//组件权限编辑器
		onColumnRef = (ref) => {
			this.columnRef = ref;
		}

		// 获取明系列表头数据
		getDetailTableColumns = () => {
			let { language } = this.state;
			let data = {
				params: [{
					compontName: 'MaterialInventoryEnterDetails',
					type: 'C',
				}]
			}
			$http.post('urlS', this, {
				code: '01040073',
				data: data,
				success: function (res) {
					if (+res.errorCode === 0) {
						let arr = res.result.C && res.result.C.length > 0 ? JSON.parse(JSON.stringify(res.result.C)).map((item, index) => {
							return {
								...item,
								key: index + 1,
								title: <div onDoubleClick={() => {
									this.setState({ takeStockListCode: 'MaterialInventoryEnterDetails' }, () => {
										// this.columnRef.onOpenModel();
									})
								}}>{language.language == 'EN' ? item.enDescripts : item.title}</div>,
								render: (text, record) => {
									if (item.code == 'takeStockNumIn') {
										return (<span><Input min={0} type="number" value={record.purQty ? record.purQty : this.state.blankFilling ? record.accPurQty : ''} onChange={(e) => this.handleFieldChange(e, 'purQty', record.ID)} style={{ float: 'left', marginLeft: '6px', width: '50%', padding: '0', paddingLeft: '5px' }} /><span style={{ verticalAlign: '-webkit-baseline-middle' }}>{record.purUnitDesc}</span></span>)
									} else if (item.code == 'takeStockNumBa') {
										return (<span><Input min={0} type="number" value={record.baseQty ? record.baseQty : this.state.blankFilling ? record.accBaseQty : ''} style={{ float: 'left', marginLeft: '6px', width: '50%', padding: '0', paddingLeft: '5px' }} onChange={(g) => { this.handleFieldChange(g, 'baseQty', record.ID) }} /><span style={{ verticalAlign: '-webkit-baseline-middle' }}>{record.baseUnitDesc}</span></span>)
									} else {
										return (<span>{text}</span>)
									}
								}
							}
						}) : '';
						let filterArr = arr.filter(function (item) { return item.display === 'Y' });
						this.setState({ columnsRight: filterArr, modalColumnTotal: res.totalWidth });

					}
				}
			});
		}

		// 打开弹框
		showModal = () => {
			this.setState({
				visible: true
			});
		}

		// 确定
		handleOk = (e) => {
			let { ChineseEnglishSize } = this.state;
			if (this.state.rowId) {
				// this.props.handleThis.getEchoData(this.state.rowId);
				this.handleCancel()
			} else {
				message.error(ChineseEnglishSize.MaterialInventoryGenerationAndselectOperatedDataTips ? ChineseEnglishSize.MaterialInventoryGenerationAndselectOperatedDataTips.descripts : "请选择一条需要操作的数据");
			}
		}

		// 关闭
		handleCancel = (e) => {
			this.setState({
				visible: false,
				status: undefined,
			});
		}

		checkData = () => {
			this.setState({
				pageSize: 10,
				page: 1,
			}, () => {
				this.getNewTakeStock()
			})
		}

		// 获取列表数据
		getNewTakeStock = () => {
			this.setState({ loading: true });
			let { ChineseEnglishSize } = this.state;
			let { page, pageSize } = this.state;
			this.props.form.validateFields((errors, values) => {
				let obj = JSON.parse(JSON.stringify(values));
				if (errors == null) {
					let data = {
						params: [
							{
								locID: obj.locDr ? obj.locDr : undefined,
								stkCatID: obj.stkCat ? obj.stkCat : undefined,
								stkSubCatID: obj.stkSubCat ? obj.stkSubCat : undefined,
								startStkBinID: undefined,
								endStkBinID: undefined,
								method: obj.methods ? obj.methods : undefined,
								serialFlag: obj.serialFlag ? 'Y' : 'N',
							}
						],
						pagination: [
							{
								pageSize: pageSize,
								currentPage: page,
								sort: "",
								dir: "",
							}
						],
					};
					$http.post('urlS', this, {
						code: "02060089",
						data: data,
						success: function (res) {
							if (+res.errorCode === 0) {
								if (res.result.rows.length > 0) {
									for (var i = 0; i < res.result.rows.length; i++) {
										res.result.rows[i].key = i + 'twig';
									}
									this.setState({ tableData: res.result.rows, total: res.result.total, loading: false });
								} else {
									this.setState({ tableData: [], total: 0, loading: false });
									message.error(ChineseEnglishSize.MaterialInventoryGenerationAndnoData ? ChineseEnglishSize.MaterialInventoryGenerationAndnoData.descripts : '没数据');
								}
							}
						},
						error: function () {
							this.setState({ tableData: [], total: 0, loading: false });
						}
					})
				}
			});
		}

		save = () => {
			this.props.form.validateFields((errors, values) => {
				let obj = JSON.parse(JSON.stringify(values));
				if (errors == null) {
					let data = {
						params: [
							{
								locID: obj.locDr ? obj.locDr : undefined,
								stkCatID: obj.stkCat ? obj.stkCat : undefined,
								stkSubCatID: obj.stkSubCat ? obj.stkSubCat : undefined,
								startStkBinID: undefined,
								endStkBinID: undefined,
								method: obj.methods ? obj.methods : undefined,
								serialFlag: obj.serialFlag ? 'Y' : 'N',
							}
						]
					};
					$http.post('urlS', this, {
						code: "02060090",
						data: data,
						success: function (res) {

							if (+res.errorCode === 0) {
								message.success(res.errorMessage);
								this.props.handleThis.getWarehouseList();
							}
						}
					})
				}
			});
		};

		// 页码改变的回调，参数是改变后的页码及每页条
		onChange = (page, pageSize) => {
			this.setState({ page: page, pageSize: pageSize }, () => {
				this.getNewTakeStock();
			})
		}

		// 条数改变的回调
		onShowSizeChange = (current, size) => {
			this.setState({ page: current, pageSize: size }, () => {
				this.onChange(current, size)
			})
		}

		// 显示分页总条数
		showTotal(total) {
			return `共 ${total} 条`;
		}

		render() {
			let { ChineseEnglishSize, columnsRight, userData, loading } = this.state;
			const { getFieldDecorator } = this.props.form;
			return (
				<Modal
					visible={this.state.visible}
					onCancel={this.handleCancel}
					width={1300}
					className="addPayment"
					footer={null}
				>
					<div className="aa" style={{ paddingBottom: '17px' }}>
						<Row>
							<Card
								size="small"
								title={ChineseEnglishSize.MaterialInventoryGenerationAndaddInventory ? ChineseEnglishSize.MaterialInventoryGenerationAndaddInventory.descripts : '新增盘点单'}
							>
								<Col span={18}>
									<Form>
										<Row >

											<Col span={7}>
												<FormItem {...formItemLayout} label={ChineseEnglishSize.MaterialInventoryGenerationAndloc ? ChineseEnglishSize.MaterialInventoryGenerationAndloc.descripts : '科室'}>
													{getFieldDecorator('locDr', {
														initialValue: userData && userData.locID ? userData.locID : undefined,
													})(
														<Select allowClear={true}>
															{this.state.stateCode.loc && this.state.stateCode.loc.map((item, i) => {
																return <Option value={item.id} key={i}>{item.descripts}</Option>
															})}
														</Select>
													)}
												</FormItem>
											</Col>
											<Col span={7}>
												<FormItem {...formItemLayout} label={ChineseEnglishSize.MaterialInventoryGenerationAndstkCat ? ChineseEnglishSize.MaterialInventoryGenerationAndstkCat.descripts : '库存大类'}>
													{getFieldDecorator('stkCat', {
														initialValue: undefined,
													})(
														<Select allowClear={true}>
															{this.state.stateCode.stkCat && this.state.stateCode.stkCat.map((item, i) => {
																return <Option value={item.id} key={i}>{item.descripts}</Option>
															})}
														</Select>
													)}
												</FormItem>
											</Col>
											<Col span={7}>
												<FormItem {...formItemLayout} label={ChineseEnglishSize.MaterialInventoryGenerationAndstkSubCat ? ChineseEnglishSize.MaterialInventoryGenerationAndstkSubCat.descripts : '库存子类'}>
													{getFieldDecorator('stkSubCat', {
														initialValue: undefined,
													})(
														<Select allowClear={true}>
															{this.state.stateCode.stkSubCat && this.state.stateCode.stkSubCat.map((item, i) => {
																return <Option value={item.id} key={i}>{item.descripts}</Option>
															})}
														</Select>
													)}
												</FormItem>
											</Col>
											<Col span={7}>
												<FormItem {...formItemLayout} label={ChineseEnglishSize.MaterialInventoryGenerationAndhuo ? ChineseEnglishSize.MaterialInventoryGenerationAndhuo.descripts : '货位码'}>
													{getFieldDecorator('huo', {
														initialValue: undefined,
													})(
														<span>
															<Input style={{ width: '45%' }} />
															<span style={{ width: '10%', textAlign: 'center', display: 'inline-block' }}>{ChineseEnglishSize.MaterialInventoryGenerationAndto ? ChineseEnglishSize.MaterialInventoryGenerationAndto.descripts : '到'}</span>
															<Input style={{ width: '45%' }} />
														</span>
													)}
												</FormItem>
											</Col>
											<Col span={7}>
												<FormItem {...formItemLayout} label={ChineseEnglishSize.MaterialInventoryGenerationAndmethods ? ChineseEnglishSize.MaterialInventoryGenerationAndmethods.descripts : '录入方式'}>
													{getFieldDecorator('methods', {
														initialValue: this.state.stateCode && this.state.stateCode.methods && this.state.stateCode.methods.length > 0 ? this.state.stateCode.methods[0].id : undefined,
														rules: [{ required: ChineseEnglishSize.MaterialInventoryGenerationAndmethods ? ChineseEnglishSize.MaterialInventoryGenerationAndmethods.required == 'Y' ? true : false : false, message: ChineseEnglishSize.MaterialInventoryGenerationAndmethods ? ChineseEnglishSize.MaterialInventoryGenerationAndmethods.message : '录入方式不能为空' }]
													})(
														<Select allowClear={true}>
															{this.state.stateCode.methods && this.state.stateCode.methods.map((item, i) => {
																return <Option value={item.id} key={i}>{item.descripts}</Option>
															})}
														</Select>
													)}
												</FormItem>
											</Col>
											<Col span={7}>
												<FormItem {...formItemLayout} label="是否晶体">
													{getFieldDecorator('serialFlag', {
														valuePropName: 'checked',
														initialValue: false
													})(
														<Switch checkedChildren="是" unCheckedChildren="否" />
													)}
												</FormItem>
											</Col>
										</Row>
									</Form>
								</Col>
								<Col span={3} style={{ marginLeft: '-50px' }}>
									<Row style={{ marginTop: '4px' }} className="buttonLeft">
										<Button onClick={this.checkData}>{ChineseEnglishSize.MaterialInventoryGenerationAndsearch ? ChineseEnglishSize.MaterialInventoryGenerationAndsearch.descripts : '查询'}</Button>
									</Row>
								</Col>
								<Col span={3} style={{ textAlign: 'right' }}>
									<Row style={{ marginTop: '4px' }} className="buttonRight">
										<Button type="primary" onClick={this.save}>{ChineseEnglishSize.MaterialInventoryGenerationAndsave ? ChineseEnglishSize.MaterialInventoryGenerationAndsave.descripts : '保存'}</Button>
									</Row>
								</Col>
							</Card>
						</Row>

						<Row style={{ margin: '0 20px' }}>
							<Col style={{ height: store.getState().tableHeight.y - 75 + 'px' }}>
								<Table
									loading={loading}
									columns={columnsRight.length > 0 ? columnsRight : this.columnsRight}
									dataSource={this.state.tableData}
									pagination={false}
									bordered
									scroll={{ x: 1000, y: store.getState().tableHeight.y - 167 }}
									style={{ height: store.getState().tableHeight.y - 117 }}
									className='listHeight'
								/>
								<Pagination
									showTotal={() => this.showTotal(this.state.total)}
									size="small"
									showQuickJumper
									showSizeChanger
									defaultCurrent={1}
									current={this.state.page}
									total={this.state.total}
									onChange={this.onChange}
									onShowSizeChange={this.onShowSizeChange}
									style={{ textAlign: "right", marginRight: '13px' }}
								/>
							</Col>
						</Row>
					</div>
				</Modal>
			)
		}
	}
);

export default AddPayment;